package cn.deppon.jd.task;

import cn.deppon.jd.pojo.Item;
import cn.deppon.jd.service.ItemService;
import cn.deppon.jd.util.HttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: ItemTask
 * @Description: TODO
 * @Author Administrator
 * @Date 2020-11-11
 * @Version 1.0
 */
@Component
public class ItemTask {
    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    ItemService itemService;
    private static final ObjectMapper mapper = new ObjectMapper();

    //当下载任务完成后, 间隔多长时间进行下一次的任务
    @Scheduled(fixedDelay = 10 * 1000)
    public void itemTask() throws Exception {
   /*     String html="";
        File file=new File("C:\\Users\\Administrator\\Desktop\\test.html");
        try {
            FileInputStream in=new FileInputStream(file);
            // size 为字串的长度 ，这里一次性读完
            int size=in.available();
            byte[] buffer=new byte[size];
            in.read(buffer);
            in.close();
            html=new String(buffer,"utf8");
        } catch (Exception e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }*/

        //声明需要解析的初始地址
        String url = "https://search.jd.com/Search?keyword=手机&suggest=1.def.0.base&wq=手机&s=116&click=0&page=";
        //按照页码对搜索结果进行遍历解析
        for (int i = 1; i < 10; i = i + 2) {
            String html = httpUtils.doGetHtml(url + i);
            //解析页面, 获取商品数据并存储
            this.parse(html);
        }

        System.out.println("完成!!!");
    }

    //解析页面, 获取商品数据并存储
    private void parse(String html) throws IOException {
        //解析html获取Document
        Document doc = Jsoup.parse(html);
        //获取spu
        Elements spuEles = doc.select("div#J_goodsList > ul >li");

        for (Element spuEle : spuEles) {
            //获取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));
            //获取sku信息
            Elements skuEles = spuEle.select("li.ps-item");
            for (Element skuEle : skuEles) {
                //获取sku
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));
                //根据sku查询
                Item item = new Item();
                item.setSku(sku);
                List<Item> list = this.itemService.findAll(item);
                if (list.size() > 0) {
                    //如果存在，进行下一个循环,该数据不保存, 因为已存在
                    continue;
                }
                //设置sku
                item.setSpu(spu);
                //获取商品详情的url
                String itemUrl = "https://item.jd.com/" + sku + ".html";
                item.setUrl(itemUrl);
                String picUrl = "https:" + skuEle.select("img[data-sku]").first().attr("data-lazy-img");
                picUrl = picUrl.replace("/n9/", "/n1/");
                String picName = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName);

                //获取商品的价格
                String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
                double price = mapper.readTree(priceJson).get(0).get("p").asDouble();

                item.setPrice(price);
                //获取商品的标题
                String itemInfo = this.httpUtils.doGetHtml(item.getUrl());
                String title = Jsoup.parse(itemInfo).select("div.sku-name").text();
                item.setTitle(title);
                item.setCreated(new Date());
                item.setUpdated(item.getCreated());
                //保存商品数据到数据库中
                this.itemService.save(item);
            }
        }
    }
}
